<?php
/**
 * 微信用户模型
 * */
namespace Mob \ Model;

use Think \ Model;
use Think \ Hook;
require_once('./Application/Mob/Common/function.php');
class WxUserModel extends Model
{

   /**
   * 判断微信用户是否已经注册
   *
   * @param $Openid
   * 微信openid
   * @return boolean true = 已注册 false=未注册
   */
  public function isregister($openid)
  {

  return $this->getWxUserUid($openid);

  }

  public function WxInit()
  {
  	if(!is_weixin())
  	{
  	return ;
  	}

   if(!is_login()) //判断用户是否没有登录
   {
   $openid = $this->getWxopenid();   //

   $Uid = $this->isregister($openid);

   if($Uid)
   {
   if(session()['user_auth']['is_logout']==1)
   {
   	return ;

   }


  $res= $this->wxUserLogin($openid);

   if($res)
   {
   return ;
   }else
   {
   return ;
   }

   }else
   {
   $res= $this->initWxUser($openid);


   }

   }


  }

  public function initWxUser($openid)
  {
  $UserInfo = $this->getWxUserInfo($openid);

  if(!$UserInfo)
  {
   return false;
  }
  $subscribe=$UserInfo['subscribe'];
  $nickname= $UserInfo['nickname'];
  $sex=$UserInfo['sex'];
  $city=$UserInfo['city'];
  $country=$UserInfo['country'];
  $province=$UserInfo['province'];
  $language=$UserInfo['language'];
  $headimgurl=$UserInfo['headimgurl'];
  $subscribe_time=$UserInfo['subscribe_time'];
  $unionid=$UserInfo['unionid'];
  $remark=$UserInfo['remark'];
  $groupid=$UserInfo['groupid'];
  $tagid_list=$UserInfo['tagid_list'];
  $this->createWxUserInfo($subscribe,$openid,$nickname,$sex,$city,$country,$province,$language,$headimgurl,$subscribe_time,$unionid,$remark,$groupid,$tagid_list);

   $member = D('Member');
   $uid = $member->registerMember($nickname);
  // print_r($uid);

   $this->updateWxUid($openid,$uid);
   $this->initWxAvatarImg($openid);

   $this->initRoleUser(1,$uid);   //执行初始化权限
   $this->WxLogin($uid);    //执行登录操作
  return true;

  }

  private function createWxUserInfo($subscribe,$OpenId,$nickname,$sex,$city,$country,$province,$language,$headimgurl,$subscribe_time,$unionid='',$remark='',$groupid='',$tagid_list='')
  {

  $data['subscribe']=$subscribe;
  $data['OpenId']=$OpenId;
  $data['nickname']=$nickname;
  $data['sex']=$sex;
  $data['city']=$city;
  $data['country']=$country;
  $data['province']=$province;
  $data['language']=$language;
  $data['headimgurl']=$headimgurl;
  $data['subscribe_time']=$subscribe_time;
  $data['unionid']=$unionid;
  $data['remark']=$remark;
  $data['groupid']=$groupid;
  $data['tagid_list']=$tagid_list;

   return $this->add($data);

  }


  public function wxUserLogin($openid)
  {


  $Uid = $this->getWxUserUid($openid);

  if($Uid&&$Uid!=0)
  {
   $this->WxLogin($Uid);
  return true;

  }else
  {
  return false;
  }




  }

  public function queryWxUserInfo($openid)
  {
  	$where['OpenId']=$openid;
  	$where['status']=1;
  	return $this->where($where)->field('UserId,subscribe,OpenId,nickname,sex,city,country,province,language,headimgurl,subscribe_time,unionid,remark,groupid,tagid_list,registerTime')->find();


  }

  public function getWxopenid()
  {
   	vendor('WxPay.WxPayPubHelper');

   	$Redpack = new \Redpack_pub();

		//=========步骤1：网页授权获取用户openid============
		//通过code获得openid
		if (!isset($_GET['code']))
		{
			//触发微信返回code码
		//	$reduct_uri = WEB_HOST."/index.php/Home/WxCashRedPack/sendRedpack";
		$baseUrl = urlencode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING']);
	   $url = $Redpack->createOauthUrlForCode($baseUrl);
       // print_r($url);
         Header("Location: $url");
		}else
		{
			//获取code码，以获取openid
			$code = $_GET['code'];
			$Redpack->setCode($code);
			$openid = $Redpack->getOpenId();
		}

       return $openid;


  }

  public function getWxUserInfo($openid)
  {

   	vendor('WxPay.WxPayPubHelper');
   $Redpack = new \JsApi_pub();
  $UserInfo= $Redpack->getWxUserInfo($openid);
  return $UserInfo;

  }


  public function getWxUserUid($openid)
  {
   return $this->queryWxUserInfo($openid)['UserId'];


  }
  private function updateWxUid($openid,$Uid)
  {
    $where['OpenId']=$openid;
    $where['status']=1;
    $data['UserId']=$Uid;
    return $this->where($where)->save($data);

  }
  public function getWxAvatarImg($openid)
  {
  $WxUserInfo = $this->queryWxUserInfo($openid);


  if(!$WxUserInfo)
  {
  return false;

  }
   $headimgurl = $WxUserInfo['headimgurl'];
   $Uid = $WxUserInfo['UserId'];
   $dir = './Uploads/Avatar/'.$Uid.'/';
    mkdir ("./Uploads/Avatar/".$Uid);
   $filename=substr($openid,0,13);
   $result= put_file_from_url_content($headimgurl,$filename.'.jpg',$dir);
   if($result)
   {
 	$SrcFile=$dir.$filename.'.jpg';
   $imagesize32 = ImageResize($SrcFile,32, $dir.$filename.'_32_32'.'.jpg', 90);
   $imagesize64 = ImageResize($SrcFile,64, $dir.$filename.'_64_64'.'.jpg', 90);
   $imagesize128 = ImageResize($SrcFile,128, $dir.$filename.'_128_128'.'.jpg', 90);
   $imagesize256 = ImageResize($SrcFile,256, $dir.$filename.'_256_256'.'.jpg', 80);
   $imagesize512 = ImageResize($SrcFile,512, $dir.$filename.'_512_512'.'.jpg', 80);
   return $filename;
   }



  }

  public function createWxAvatarImg($openid,$imgfile,$extension='jpg')
  {
  	$Uid = $this->getWxUserUid($openid);
    $avatar = M('avatar');
    $where['uid']=$Uid;
    $where['status']=1;
    $res = $avatar->where($where)->find();
    if($res)
    {
    $data['path']='/'.$Uid.'/'.$imgfile.'.'.$extension;
    return $avatar->where($where)->save($data);
    }else
    {
    $data['uid']=$Uid;
  	$data['path']='/'.$Uid.'/'.$imgfile.'.'.$extension;
  	$data['driver']='local';
  	$data['create_time']=time();
  	$data['status']=1;
    return $avatar->add($data);
    }
    clean_query_user_cache($Uid, array('avatar256', 'avatar128', 'avatar64', 'avatar32', 'avatar512'));   //执行清理缓存操作


  }

  public function initWxAvatarImg($openid)
  {
  //print_r($openid);
  $filename =$this->getWxAvatarImg($openid);

  if($filename)
  {
  $res =$this->createWxAvatarImg($openid,$filename);
  return $res;
  }else
  {
  return false;
  }

  }

  public function WxUserLogOut()
  {

  	    $data= array('WxUser'=> array('login'=>0,'is_logout'=>1));
        session('_AUTH_LIST_' . get_uid() . '1', null);
        session('_AUTH_LIST_' . get_uid() . '2', null);
        session('user_auth', null);
        session('user_auth', $data);
        session('user_auth_sign', null);
        cookie('OX_LOGGED_USER', NULL);





  }
  public function WxLogin($Uid)
  {   $user = D('Member')->field(true)->find($Uid);
     if(!$user || 1 != $user['status']) {
            $this->error = L('_USERS_DO_NOT_EXIST_OR_HAVE_BEEN_DISABLED_WITH_EXCLAMATION_'); //应用级别禁用
            return false;
        }                //记录行为
        action_log('wxuser_login', 'member', $uid, $uid);
       $count = M('wx_user')->where('UserId='. $Uid . ' and status = 1')->count();
       $openid = $this->queryWxUserOpenId($Uid);


        /* 记录登录SESSION和COOKIES */
        $auth = array(
            'uid'             => $user['uid'],
            'username'        => $user['nickname'],
            'last_login_time' => $user['last_login_time'],
            'WxUser'=> array(
            'is_wxuser' =>$count,
            'wx_openid'=>$openid,
            'login'=>1,
            'is_logout'=>0,
              ),

        );
        session('user_auth', $auth);
        session('user_auth_sign', data_auth_sign($auth));
  }

  public function queryWxUserOpenId($Uid)
  {

   return	$this->where('UserId = '.$Uid.' and status =1')->getField('OpenId');

  }


    private function initRoleUser($role_id = 0, $uid)
    {
        $memberModel = D('Member');
        $role = D('Role')->where(array('id' => $role_id))->find();
        $user_role = array('uid' => $uid, 'role_id' => $role_id, 'step' => "start");
        if ($role['audit']) { //该角色需要审核
            $user_role['status'] = 2; //未审核
        } else {
            $user_role['status'] = 1;
        }
        $result = D('UserRole')->add($user_role);
        if (!$role['audit']) { //该角色不需要审核
            $memberModel->initUserRoleInfo($role_id, $uid);
        }
        $memberModel->initDefaultShowRole($role_id, $uid);

        return $result;
    }

   public function initUserInfo($userinfo)
    {

  $subscribe=0;
  $nickname= $userinfo['nickname'];
  $openid= $userinfo['openid'];
  $sex=$userinfo['sex'];
  $city=$userinfo['city'];
  $country=$userinfo['country'];
  $province=$userinfo['province'];
  $language=$userinfo['language'];
  $headimgurl=$userinfo['headimgurl'];
  $subscribe_time=$userinfo['subscribe_time'];
  $unionid=$userinfo['unionid'];
  $remark=$userinfo['remark'];
  $groupid=$userinfo['groupid'];
   $tagid_list=$userinfo['tagid_list'];
  $this->createWxUserInfo($subscribe,$openid,$nickname,$sex,$city,$country,$province,$language,$headimgurl,$subscribe_time,$unionid,$remark,$groupid,$tagid_list);

   $member = D('Member');
   $uid = $member->registerMember($nickname);
  // print_r($uid);

   $this->updateWxUid($openid,$uid);
   $this->initWxAvatarImg($openid);

   $this->initRoleUser(1,$uid);   //执行初始化权限

    }

   public function getUserInfo($uid)
   {
    $where = array('UserId'=>$uid,'status'=>1);
    return $this->where($where)->field('OpenId,nickname,sex,subscribe,city,country,province,language,headimgurl')->find();
   }
   public function updateWxAvatarImg($uid,$imgUrl)
   {
   	$where = array('UserId'=>$uid,'status'=>1);
   	$this->where($where)->save(array('headimgurl'=>$imgUrl));
   }




}